package servlets;

import java.io.IOException;
import java.util.SortedSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MockUserRepo;
import model.User;
import model.UserRepo;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
  private UserRepo user_repo = MockUserRepo.getInstance();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SortedSet<User> users = user_repo.getUsers();
		
		RequestDispatcher dispacher;
    request.setAttribute("users", users);
    dispacher = getServletContext().getRequestDispatcher("/users.jsp");
    dispacher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name, mail, pass1, pass2;
		RequestDispatcher dispacher;

		name = (String)request.getParameter("name");
		mail = (String)request.getParameter("mail");
		pass1 = (String)request.getParameter("pass1");
		pass2 = (String)request.getParameter("pass2");
 
		if(pass1.equals(pass2)){
		  user_repo.addUser(name, pass1, mail);
		  request.setAttribute("added", true);
		  request.setAttribute("addedname", name);
		} else {
		  request.setAttribute("added", false);
		  request.setAttribute("error", "Password verification fail!");
		  request.setAttribute("mail", mail);
		  request.setAttribute("name", name);
		}

		request.setAttribute("users", user_repo.getUsers());

    dispacher = getServletContext().getRequestDispatcher("/users.jsp");
    dispacher.forward(request, response);
	}

}
